package com.uzhie.jt808.task;

import com.alibaba.fastjson.JSONObject;
import com.uzhie.jt808.JT808Constant;
import com.uzhie.jt808.service.JT808ServiceImpl;
import com.uzhie.media.MediaConstant;
import com.uzhie.media.service.MediaPostServiceImpl;
import org.apache.log4j.Logger;

import java.util.concurrent.ExecutionException;

/**
 * Created by TangFei on 2018/8/12.
 * 调用流媒体服务器查询在线通道数
 */
public class MediaOnLineNumTask implements Runnable {

    private Logger logger = Logger.getLogger(getClass());

    private String vehicleNo;
    private int channelNumber;
    private String simNo;
    private String deviceId;
    private int playType;
    private byte[] body;

    private MediaPostServiceImpl<Integer> mediaPostService;
    private JT808ServiceImpl jt808PostService;

    public MediaOnLineNumTask(String vehicleNo, int channelNumber, String simNo, String deviceId, int playType,byte[] body) {
        this.vehicleNo = vehicleNo;
        this.channelNumber = channelNumber;
        this.simNo = simNo;
        this.deviceId = deviceId;
        this.playType = playType;
        this.body = body;
    }

    public void setService(JT808ServiceImpl jt808PostService, MediaPostServiceImpl mediaPostService) {
        this.jt808PostService = jt808PostService;
        this.mediaPostService = mediaPostService;
    }

    @Override
    public void run() {
        // 关闭直播 判断当前连接数
        JSONObject object = new JSONObject();
        object.put("vehicleNo", vehicleNo);
        object.put("channelNumber", channelNumber);
        object.put("simNo", simNo);
        object.put("deviceId", deviceId);
        object.put("playType", playType);
        // 发送消息到流媒体服务器 获取在线通道数
        Integer result = 0;
        try {
            result = mediaPostService.postWithResult(MediaConstant.MSG_ID.PLA_REQ_ONLINE_CHANNEL, object);
        } catch (ExecutionException e) {
            result = 0;
            logger.error(e);
        } catch (InterruptedException e) {
            result = 0;
            logger.error(e);
        } finally {
            logger.info("得到的结果是：" + result);
            if (result <= 1) {
                boolean post = jt808PostService.postForMedia(JT808Constant.MSG_ID.PLA_REQ_MONITOR_CONTROL, simNo, body);
                logger.info("当前通道将关闭 结果为：" + post);
            }
        }
    }
}
